<?php
namespace Modules\Activity\Http\Controllers\Client\Choushang;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Choushang\Activity;
use \Modules\Activity\Entities\ActivityOrder as Order;

use Modules\Activity\Entities\Ticket;
use Modules\Activity\Entities\TicketRecord;
use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;


// 抽赏订单
class OrderController extends Controller
{
    // 创建订单
    public function preview(Request $req)
    {
        $rule = [
            'activity_id' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        // $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');


        // 抽赏
        $activity = Activity::getEntity([
            'id' => $req->activity_id
        ]);

        // 购买总数
        $total = $req->total;

        // 检查是否超出限售
        $activity->checkSkuStock($total) || ThrowException::Conflict('库存不足~');

        // 检查是否超出限售
        // $activity->checkSaleLimit($total);

        // 检查次数限制
        // $activity->checkPerUserLimit($user, $total);

        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
        ]);

        // 返回订单内容
        return $order->generatePreviewResponse($user);
    }

    // 创建订单
    public function confirm(Request $req)
    {
        $rule = [
            'activity_id' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();
        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'create_order', 1);

        // 抽赏
        $activity = Activity::getEntity([
            'id' => $req->activity_id
        ]);

        // 购买总数
        $total = $req->total;

        $activity->status == 1 || ThrowException::Conflict('活动已下架~');

        // 检查是否超出限售
        $activity->checkSkuStock($total) || ThrowException::Conflict('库存不足~');

        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        $is_last = $activity->checkSkuStockAll($total);
        //if ( $is_last && $activity->last_open_time > time() ){
        if ( $activity->last_open_time > time() ){
            // 榜一保护期
            $bang1=DB::table('orders')->where(array('node_id' => $req->activity_id, 'node_type'=> 'choushang'))->groupBy('user_id')->orderBy('totals', 'desc')->first(
                array(
                    \DB::raw('SUM(sku_total) as totals'),  'user_id'
                )
            );

            if ( $user->id != $bang1->user_id ){
                $p = round(($activity->last_open_time - time())/60);
                echo json_encode(array('code'=>222, 'msg'=>"当前时间为榜一保护期，剩余时间：$p 分钟。"));die;
            }
        }
        DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');

        $sharer = 0;
        if ( $req->input('sharer') ){
            $s = DB::table('users')->where('uuid', $req->sharer)->first();
            $s_init = object_to_array($s);
            $sharer = $s_init['id'];
        }

        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
            'sharer' => $sharer,
        ]);

        // 使用免费次数兑换
        if ($req->input('is_use_free_ticket') && $req->input('ticket_id') && $total === 1) {
            $ticket = Ticket::getEntity([
                'id' => $req->ticket_id
            ]);

            $newStock = $ticket->stock - $total;

            $newUseTotal = $ticket->used_total;
            $newUseTotal += $total;

            if ($newStock < 0) {
                DB::rollBack();
                return false;
            }

            $ticket->update([
                'stock' => $newStock,
                'total' => $ticket->total + $total,
                'used_total' => $newUseTotal,
            ]);

            TicketRecord::create([
                'user_id' => $user->id,
                'node_id' => $activity->id,
                'node_type' => 'choushang',
                'node_uuid' => $activity->uuid,
                'type' => 2,
                'total' => $total,
                'after_total' => $newStock,
                'description' => '使用扣除'
            ]);

            $order->useFreeTicket();
        }

        $order->createAll();
        if ( $is_last ){
            DB::update('update orders set is_last = 1 where id = ? ',[$order->id]);
        }

        DB::commit();

        // 返回订单内容
        $res = $order->generateResponse();
        return $res;
    }

    // 试一试
    public function try(Request $req)
    {
        $rule = [
            'activity_id' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        // $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

        // 福袋
        $activity = Activity::getEntity([
            'id' => $req->activity_id
        ]);

        // 购买总数
        $total = $req->total;

        // 仅仅
        DB::beginTransaction();

        // 取出sku
        $skuMaps = $activity->pickLuckySkusForTry($total, $user, null);

        $list = [];

        // 此处不要提交到数据库保存
        foreach ($skuMaps as $skuMap) {
            $sku = $skuMap['skuable'];
            array_push($list, [
                "title" => $sku->title,
                "number" => $sku->number,
                "thumb" => $sku->thumb,
                "money_price" => $sku->money_price,       // 价值 (人民币)
                "total" => $skuMap['total'],                 // 中奖数量
            ]);
        }

        $uuid = 'try_' . uniqid();

        $cached = [
            'sku_type' => 'choushang_sku',
            'sku_id' => $skuMaps[0]['skuable']->id,
            'skus' => $list
        ];
        Cache::put($uuid, $cached, 1800);

        return [
            'package_uuid' => $uuid,
            // 'skus' => $list
        ];

    }
}
